package com.fresh.common.resolver;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.fresh.auth0.TokenGenerator;
import com.fresh.common.annotation.LoginUser;
import com.fresh.entity.UserEntity;
import com.fresh.utils.CookieManager;

public class LoginUserArgumentResolver implements HandlerMethodArgumentResolver {

	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterAnnotation(LoginUser.class) != null;
	}

	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		String token = webRequest.getHeader("token");
		if (StringUtils.isEmpty(token)) {
			token = webRequest.getParameter("token");
		}
		if (StringUtils.isEmpty(token)) {
			token = new CookieManager(webRequest.getNativeRequest(HttpServletRequest.class), null).getCookie("token");
		}
		if (StringUtils.isEmpty(token)) {
			return null;
		}
		UserEntity member=new UserEntity();
		member.setId(TokenGenerator.getClaim(token,"USER_ID").asString());
		member.setName(TokenGenerator.getClaim(token,"USER_NAME").asString());
		return member;
	}

}